#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <assert.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

int main()
{
    // 1、创建匿名管道
    int pipefd[2];
    int ret = pipe(pipefd);
    assert(ret != -1);
    (void)ret;

    // 2、创建子进程
    pid_t id = fork();
    if (id == 0)
    {
        // 子进程：关闭写端，只留读端
        close(pipefd[1]);

        // 进程进程间通信
        char read_buffer[1024 * 8] = {0};
        while (true)
        {
            ssize_t re = read(pipefd[0], read_buffer, sizeof(read_buffer) - 1);
            if (re > 0)
            {
                read_buffer[re] = 0;
                printf("child pid: %d, get a message: %s\n", getpid(), read_buffer);
            }
            else if (re == 0)
            {
                cout << "child: end of the file. quit." << endl;
                break;
            }
            else
            {
                cout << "child : error!" << endl;
                break;
            }
        }

        // 通信完毕
        close(pipefd[0]);
        exit(0);
    }

    // 父进程：关闭读端，只留写端
    close(pipefd[0]);

    // 进程进程间通信
    int count = 0; // 写入次数
    char write_buffer[1024 * 8] = {0};
    string message = "父进程写入数据";

    while (true)
    {
        snprintf(write_buffer, sizeof(write_buffer), "father pid:%d, %s , 第%d次写入.\n", getpid(), message.c_str(), ++count);
        write(pipefd[1], write_buffer, strlen(write_buffer));
        sleep(1);
        if (count == 10)
        {
            cout << "father quie!" << endl;
            break;
        }
    }

    // 通信完毕
    close(pipefd[1]);
    pid_t ret2 = waitpid(id, nullptr, 0);
    printf("wait:%d, childepid:%d, conunt:%d\n", ret2, id, count);
    assert(ret2 > 0);
    (void)ret2;
    return 0;
}